package com.tanhua.admin.listener;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.model.mongo.Movement;
import com.tanhua.service.MovementApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author げっしょく
 * @date 2021/11/5
 */
@Component
public class MovementListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.audit.queue",
                            declare = "true"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "audit.movement"
            )
    )
    public void sendMovement(String movementId) throws Exception {
        //根据动态Id查找出动态
        Movement movement = movementApi.getById(new ObjectId(movementId));
        //判断动态是否为空
        if (movement != null) {
            //动态不为空取出动态文案和图片进行审核
            String textContent = movement.getTextContent();
            List<String> medias = movement.getMedias();
            Map<String, String> textScan = aliyunGreenTemplate.greenTextScan(textContent);
            Map imageScan = aliyunGreenTemplate.imageScan(medias);
            //审核不出来就是0
            int state = 0;
            //判断审核是否通过
            if (!CollUtil.isEmpty(textScan) && !CollUtil.isEmpty(imageScan)) {
                String s = textScan.get("suggestion");
                String suggestion = (String) imageScan.get("suggestion");
                if ("block".equals(s) || "block".equals(suggestion)) {
                    //没通过将动态的状态设为2
                    state = 2;
                } else if ("pass".equals(s) && "pass".equals(suggestion)) {
                    //通过将动态的状态设为1
                    state = 1;
                }
            }
            movementApi.updateMovementState(movement, state);
        }

    }

}
